import { useContext } from "react";
import { AppleContext } from "./context/appleConText";
import "./App.css";
import { observer } from 'mobx-react'
import appleImg from "./image/apple.png";
function App(props) {
  const { apples, currentTotalWeight, currentTotal, save, eat, saveLoading, eatTotal, eatTotalWeight, eatApples } = useContext(AppleContext);
  const getApple = () => {
    let No = parseInt(Math.random() * 1000);
    let weight = parseInt(Math.random() * 500);
    let applesNo = apples.concat(eatApples).map(item => item.No);
    while (applesNo.includes(No)) {
      No = parseInt(Math.random() * 1000)
    }
    return {
      No,
      weight
    }
  }
  return (
    <div className="App">
      <h3>苹果篮子</h3>
      <div className="flex total">
        <div>
          <h5>当前</h5>
          {currentTotal}个苹果，{currentTotalWeight}克
        </div>
        <div>
          <h5>已吃掉</h5>
          {eatTotal}个苹果，{eatTotalWeight}克
        </div>
      </div>
      {apples.length > 0 ? (
        <ul className='apples'>
          {apples.map((apple) => (
            <li key={apple.No} className="flex apple">
              <div>
                <img src={appleImg} alt="apple" />
              </div>
              <div>
                <h6>红苹果-{apple.No}号</h6>
                {apple.weight}g
              </div>
              <div>
                <button onClick={() => eat(apple)}>吃掉</button>
              </div>
            </li>
          ))}
        </ul>
      ) : (
        <h3>篮子里空空如也了</h3>
      )}
      <div>
        <button disabled={saveLoading} onClick={() => {
          save(getApple())
        }}>摘苹果</button>
      </div>
    </div>
  );
}

export default observer(App);
